package org.jsola.hr.common.oneKeyPay;

import com.alibaba.fastjson.JSON;
import com.alipay.api.AlipayApiException;
import com.alipay.api.AlipayClient;
import com.alipay.api.CertAlipayRequest;
import com.alipay.api.DefaultAlipayClient;
import com.alipay.api.domain.AlipayFundTransCommonQueryModel;
import com.alipay.api.request.*;
import com.alipay.api.response.*;
import lombok.extern.slf4j.Slf4j;
import org.jsola.common.DateKit8;
import org.jsola.common.StrKit;
import org.jsola.exception.ParamException;
import org.jsola.hr.vo.payAli.safetyPay.*;

import java.util.Date;
import java.util.UUID;

@Slf4j
public class AliSafetyPay {

    //支付宝网关（固定）。
    public static final String URL = "https://openapi.alipay.com/gateway.do";
    //APPID 即创建小程序后生成。
    public static final String APPID = "2021002196647967";
    //开发者私钥，由开发者自己生成。
    public static final String APP_PRIVATE_KEY = "MIIEvQIBADANBgkqhkiG9w0BAQEFAASCBKcwggSjAgEAAoIBAQCyBEoeeqKa5WwI2xHzv4pQ2UmjWXlK/QigYSSRAQoehK5XCwMH2aQGevg0o0feRJ1f/WLVSYgci8YI3JqwWRw3JpFPWCJv1kzINlFDkYX9q4FfOednlIWCkCm0PMcK8PkaHPCpNgDWr35bDtRlWSvUIaI7eBb+7ZVObTD+oqjXtHZ9NWKnFkGMURsTZg9Xl+caiW4fOy9gb0/MwBNQx9hBIdg7UrCpYHKhfnuPtEp3vvF64EFKH65bjNNksIVB8Tw1k229lVNY6BXeU5a/mfFp4bRGC+aJq4RcP5nfMLkJZ/WId3Rh/PA2bBnOvRxKnUoK8NS+MZHTv6K0zKT55S3VAgMBAAECggEALxvBfYVYiIMT7tgCTS2v7atCuG6SEY0afk6WvaS3x9G2zSQF3krzBCAAlPVsrF4eA2vrfqPh2CQI+QlgCjDaraGQLJ4XJt9gHE97e9UDz1hWeRu6qAd+uUlrL94xkiyozwc/jJfU6vswBerLvDI3zgBEjVY/R6EZtNJid9AVvFb8q8WpYyehdavbkn9vKPaq0uh/TLVj0ceM2FDTjZzIL0WCFbWc/PWBtXzXm9l4i6Y0QChhjuoQZtdp725Ye+P0JL6Sz1RcgQZToWI6f287pWB3v7UYKA4lXIHAcpM6TYrniUD7uHFy8YyRarX/NQjDsBPsyWLg9hyR8YGlA733lQKBgQDtwgbi4khwR54ArVbUXg4I9F7qJm0DUhbBkPdWKP+p4u4t/3VPoTvAWesre69ngRr6siqgDWGZnB6Du7SgckSD9cCM79Dk6xYzGPaAOBzBGnQxtHhHxTHQy3FyfytJWo3DAKZotlz9jWfVGXCh1Kz26oQ9ZVjZI33OOcvV9xDAbwKBgQC/rNgDFddyg1cykmqMBYMj0ABa45Vog7wUbYEIKhChj+CKYFvAnZdV0Rh0oYgXXPtwbI/gGZol6oztxHb8rSCjKQl0xPtjlrXYUw55AT3gqmmzKMafFwtA5H+ceCF4HWyFofNdg4vSrFSRmBhq4yurBBa6fQfc6YHY/wgXxu4P+wKBgFFY3HBOSciYyFek9xtsHtMzgTIN+ah0MrMBvY5uMqNWsHVufR3EpaP3X/4dsHLyel+iC/F9ApLDFrGtzGxFDGo18C6IcumQAaVz+gr+p9/uBClpfOnZb2Tn5qXtGstbPzukAku7cW+TLR59OMs18AP/U0WKYm7QtN+VaMeJY+LjAoGABAG++kGIoXIxbnM1Gvw6g5MjjsLXKromQl8PpXYLpvT1Aq+E+3/P3BFk63s89xAQiYcbctnWKRjAHXBP9HRCDGcdNX2wq6JI5t7FnK3z9zBYyU/+5vB6Yb7lFAZG3NXwoNKD3d6UG7FSi0Ccsg9RqF+LghZ/BZU0C685IhYcf+UCgYEAlRaa19YTX0AEQS6nuA8rQtaushf4WPmKaYNDoZACOiEee9FwJzDS0yLrm4VcKjbTtDM2T695BpU3YogSz4mWXVh4Tpojc5y1fMYDS1zvdyeMRs8LM1OKSW+Mliw5ZqgQ12RXBAkbUDDUpeFlEKnBoXYl1P/1EPohEKMe7wQxS9Y=";
    //参数返回格式，只支持 JSON 格式。
//    public static final String FORMAT = "JSON";
    //编码集，支持 GBK/UTF-8。
//    public static final String CHARSET = "UTF-8";
    //商户生成签名字符串所使用的签名算法类型，目前支持 RSA2 和 RSA，推荐使用 RSA2。
//    public static final String SIGN_TYPE = "RSA2";
    public static final String APP_CERT_PATHAPP_CERT_PATH = "D:\\payAliSafety\\appCertPublicKey_2021002196647967.crt";
    public static final String ALIPAY_CERT_PATH = "D:\\payAliSafety\\alipayCertPublicKey_RSA2.crt";
    public static final String ALIPAY_ROOT_CERT_PATH = "D:\\payAliSafety\\alipayRootCert.crt";

    public static void main(String[] args) throws AlipayApiException {

        // 公共参数
        CertAlipayRequest certAlipayRequest = buildCertAlipayRequest(URL, APPID, APP_PRIVATE_KEY,
                APP_CERT_PATHAPP_CERT_PATH, ALIPAY_CERT_PATH, ALIPAY_ROOT_CERT_PATH);

        String loginId = "399158633@qq.com";
//        String loginId = "jpkj_xqjr@163.com";

        // 根据 登录账号 获取授权的 url（注：该账号的签约号可以自定义，现在默认使用登录账号作为签约号）;   参数：1: 公共参数 2: 支付宝登录账号
//        String url = createUrl(certAlipayRequest, loginId);
//        System.out.println(url);

        // 根据 签约号 获取 协议号;   参数：1: 公共参数 2: 签约号
        AlipayUserAgreementQueryResponse alipayUserAgreementQueryResponse = selectAgreementNo(certAlipayRequest, loginId);
        String agreementNo = alipayUserAgreementQueryResponse.getAgreementNo();
        // 开通 单笔转账到户的 记账本;   参数：1: 公共参数 2: 支付宝登录账号 3: 协议号
//        String accountBookId = createAccountBook(certAlipayRequest, loginId, agreementNo);
//        System.out.println(accountBookId);

//        String accountBookId = "2088410285335863";
        String accountBookId = "2088410300144849";
        // 向记账本里面转钱;   参数：1: 公共参数 2: 记账本id 3: 协议号  4:需要充值的金额
//        String transferUrl = transferToBook(certAlipayRequest, accountBookId, agreementNo, 197);


//        String agreementNo = "399158633@qq.com";
        // 查询记账本id;   参数：1: 公共参数 2: 记账本id 3: 协议号
//        AccountBookQueryVO accountBookQueryVO = selectAccountBook(certAlipayRequest, accountBookId, agreementNo);
//        System.out.println(accountBookQueryVO.toString());

        // 批量转账到户
//        payBatch(certAlipayRequest);

        // 单笔转账到户;   参数：1: 公共参数 2: 协议号 3: 记账本id
//        SafetyPayVO safetyPayVO = new SafetyPayVO();
//        safetyPayVO.setOutBizNo("213132");
//        safetyPayVO.setTransAmount("0.01");
//        safetyPayVO.setProductCode("SINGLE_TRANSFER_NO_PWD");
//        safetyPayVO.setBizScene("ENTRUST_TRANSFER");
//        safetyPayVO.setOrderTitle("代发");
//        safetyPayVO.setRemark("代发");
//        SafetyPayerInfoVO safetyPayerInfoVO = new SafetyPayerInfoVO();
//        safetyPayerInfoVO.setExtInfo("{\"agreement_no\":\"" + agreementNo + "\"}");
//        safetyPayerInfoVO.setIdentity(accountBookId);
//        safetyPayerInfoVO.setIdentityType("ACCOUNT_BOOK_ID");
//        SafetyPayeeInfoVO safetyPayeeInfoVO = new SafetyPayeeInfoVO();
//        safetyPayeeInfoVO.setName("吴鸿");
//        safetyPayeeInfoVO.setIdentity("1573996686");
//        safetyPayeeInfoVO.setIdentityType("ALIPAY_LOGON_ID");
//        safetyPayVO.setPayerInfo(safetyPayerInfoVO);
//        safetyPayVO.setPayeeInfo(safetyPayeeInfoVO);
//        System.out.println(JSON.toJSONString(safetyPayVO));
//        long startTime = System.currentTimeMillis();
//        //核心线程数
//        int corePoolSize = 3;
//        //最大线程数
//        int maximumPoolSize = 3;
//        //超过 corePoolSize 线程数量的线程最大空闲时间
//        long keepAliveTime = 10;
//        //以秒为时间单位
//        TimeUnit unit = TimeUnit.SECONDS;
//        //创建工作队列，用于存放提交的等待执行任务
//        BlockingQueue<Runnable> workQueue = new ArrayBlockingQueue<Runnable>(10);
//        ThreadPoolExecutor threadPoolExecutor = new ThreadPoolExecutor(corePoolSize,
//                maximumPoolSize, keepAliveTime, unit, workQueue, new ThreadPoolExecutor.AbortPolicy());
//        ExecutorService singleThreadExecutor = Executors.newSingleThreadExecutor();
//        singleThreadExecutor.execute(() -> {
//            for (int i = 0; i < 10; i++) {
//                SafetyPayResultVO safetyPayResultVO = payOne(certAlipayRequest, safetyPayVO);
//                System.out.println(safetyPayResultVO.toString());
//                if (i == 5) {
//                    throw new ParamException("s");
//                }
//            }
//        });
//        for (int i = 0; i < 10; i++) {
//            threadPoolExecutor.submit(() -> {
//                payOne(certAlipayRequest, safetyPayVO);
//            });
//        }
//        long endTime = System.currentTimeMillis();
//        System.out.println("耗时：" + (endTime - startTime));
//        singleThreadExecutor.shutdown();
//        threadPoolExecutor.shutdown();


//        String orderId = "2021112513490001";
        // 查询单笔转账到户;   参数：1: 公共参数 2: 商户自定义订单id
//        BizContentSafety bizContentSafety = selectPayOne(certAlipayRequest, orderId);
//        System.out.println("=====================");
//        System.out.println(bizContentSafety.toString());

        // 查询批量转账到户
//        AlipayFundBatchDetailQueryResponse alipayResponse = selectPayBatch(certAlipayRequest, "202112170001whahy0002", "agreementNo");
//        System.out.println(alipayResponse.toString());


//        payOneToBankCard(certAlipayRequest, agreementNo, accountBookId);
        SafetyPayOneVO safetyPayOneVO = new SafetyPayOneVO();
        safetyPayOneVO.setOutBizNo("20211222whahy0001");
        safetyPayOneVO.setTransAmount("0.1");
        safetyPayOneVO.setOrderTitle("20211224银行代发测试标题");
        safetyPayOneVO.setRemark("20211224银行代发测试备注");
        SafetyPayerInfoVO safetyPayerInfoVO = new SafetyPayerInfoVO();
        safetyPayerInfoVO.setExtInfo("{\"agreement_no\":\"" + agreementNo + "\"}");
        safetyPayerInfoVO.setIdentity(accountBookId);
        SafetyPayeeInfoVO safetyPayeeInfoVO = new SafetyPayeeInfoVO();
        safetyPayeeInfoVO.setName("吴鸿");
        safetyPayeeInfoVO.setIdentity("6214835663660411");
        safetyPayOneVO.setPayerInfo(safetyPayerInfoVO);
        safetyPayOneVO.setPayeeInfo(safetyPayeeInfoVO);
//        payOne(certAlipayRequest, safetyPayOneVO);
        payOneToBankCard(certAlipayRequest, safetyPayOneVO);

    }

    public static CertAlipayRequest buildCertAlipayRequest(String url, String appId, String appPrivateKey,
                                                           String appCertPath, String alipayCertPath,
                                                           String alipayRootCertPath) {

        CertAlipayRequest certAlipayRequest = new CertAlipayRequest();
        certAlipayRequest.setServerUrl(url);
        certAlipayRequest.setAppId(appId);
        certAlipayRequest.setPrivateKey(appPrivateKey);
        certAlipayRequest.setFormat("JSON");
        certAlipayRequest.setCharset("UTF-8");
        certAlipayRequest.setSignType("RSA2");
        certAlipayRequest.setCertPath(appCertPath);
        certAlipayRequest.setAlipayPublicCertPath(alipayCertPath);
        certAlipayRequest.setRootCertPath(alipayRootCertPath);
        return certAlipayRequest;
    }


    // 生成授权链接
    public static String createUrl(CertAlipayRequest certAlipayRequest, String loginId) {
        try {
            AlipayClient alipayClient = new DefaultAlipayClient(certAlipayRequest);
            AlipayUserAgreementPageSignRequest request = new AlipayUserAgreementPageSignRequest();
            request.setBizContent("{" +
                    "    \"external_logon_id\": \"" + loginId + "\"," +
                    "    \"personal_product_code\": \"FUND_SAFT_SIGN_WITHHOLDING_P\"," +
                    "    \"sign_scene\": \"INDUSTRY|SATF_ACC\"," +
                    "    \"external_agreement_no\": \"" + loginId + "\"," +
                    "    \"third_party_type\": \"PARTNER\"," +
                    "    \"product_code\": \"FUND_SAFT_SIGN_WITHHOLDING\"," +
                    "    \"access_params\":{\"channel\":\"QRCODE\"}" +
                    "}");
            //通过alipayClient调用API，获得对应的response类
            AlipayUserAgreementPageSignResponse response = alipayClient.pageExecute(request, "get");
            log.info("调用支付宝生成授权链接接口返回信息:{}", response.getBody());
            if (response.isSuccess()) {
                return response.getBody();
            } else {
                log.error("调用支付宝生成授权链接错误，返回信息{}", response.getBody());
                throw new ParamException("调用支付宝生成授权链接错误! 错误信息：" + response.getMsg());
            }
        } catch (AlipayApiException e) {
            log.error("调用支付宝生成授权链接错误，e{}", e.getMessage());
            throw new ParamException("调用支付宝生成授权链接错误!" + e.getMessage());
        }
    }

    // 根据签约号查询协议号
    public static AlipayUserAgreementQueryResponse selectAgreementNo(CertAlipayRequest certAlipayRequest, String loginId) {
        try {
            AlipayClient alipayClient = new DefaultAlipayClient(certAlipayRequest);
            AlipayUserAgreementQueryRequest request = new AlipayUserAgreementQueryRequest();
            request.setBizContent("{" +
                    "    \"personal_product_code\": \"FUND_SAFT_SIGN_WITHHOLDING_P\"," +
                    "    \"sign_scene\": \"INDUSTRY|SATF_ACC\"," +
                    "    \"product_code\": \"FUND_SAFT_SIGN_WITHHOLDING\"," +
                    "    \"external_agreement_no\": \"" + loginId + "\"," +
                    "    \"third_party_type\": \"PARTNER\"" +
                    "}");
            //通过alipayClient调用API，获得对应的response类
            AlipayUserAgreementQueryResponse response = alipayClient.certificateExecute(request);
            log.info("调用支付宝查询协议号：结果{}", response.getBody());
            if (!response.isSuccess()) {
                throw new ParamException("调用支付宝查询协议号错误，支付宝返回结果：" + response.getSubMsg());
            }
            return response;
        } catch (AlipayApiException e) {
            log.error("调用支付宝查询协议号错误，e{}", e.getMessage());
            throw new ParamException("调用支付宝查询协议号错误!" + e.getMessage());
        }
    }

    // 记账本开通
    public static String createAccountBook(CertAlipayRequest certAlipayRequest, String loginId, String agreementNo) {
        try {
            AlipayClient alipayClient = new DefaultAlipayClient(certAlipayRequest);
            AlipayFundAccountbookCreateRequest request = new AlipayFundAccountbookCreateRequest();
            request.setBizContent("{" +
                    "    \"scene_code\": \"SATF_FUND_BOOK\"," +
                    "    \"merchant_user_id\": \"" + loginId + "\"," +
                    "    \"merchant_user_type\": \"BUSINESS_ORGANIZATION\"," +
                    "    \"ext_info\": \"{\\\"agreement_no\\\":\\\"" + agreementNo + "\\\"}\"" +
                    "}");
            AlipayFundAccountbookCreateResponse response = alipayClient.certificateExecute(request);
            log.info("调用支付宝记账本开通：结果{}", response.getBody());
            String accountBookId = response.getAccountBookId();
            if (StrKit.isEmpty(accountBookId)) {
                throw new ParamException("记账本开通失败，支付宝返回结果：" + response.getSubMsg());
            }
            return accountBookId;
        } catch (AlipayApiException e) {
            log.error("调用支付宝记账本开通失败，e{}", e.getMessage());
            throw new ParamException("调用支付宝记账本开通失败!" + e.getMessage());
        }
    }

    // 向记账本里面转钱
    public static String transferToBook(CertAlipayRequest certAlipayRequest, String accountBookId,
                                        String agreementNo, double money) {
        try {
            //获得初始化的AlipayClient
            AlipayClient alipayClient = new DefaultAlipayClient(certAlipayRequest);
            AlipayFundTransPagePayRequest request = new AlipayFundTransPagePayRequest();
            request.setBizContent("{" +
                    "    \"payee_info\": {" +
                    "        \"identity\": \"" + accountBookId + "\"," +
                    "        \"identity_type\": \"ACCOUNT_BOOK_ID\"," +
                    "        \"ext_info\": \"{\\\"agreement_no\\\":\\\"" + agreementNo + "\\\"}\"" +
                    "    }," +
                    "    \"remark\": \"备注\"," +
                    "    \"product_code\": \"FUND_ACCOUNT_BOOK\"," +
                    "    \"trans_amount\": " + money + "," +
                    "    \"biz_scene\": \"SATF_DEPOSIT\"," +
                    "    \"out_biz_no\": \"" + UUID.randomUUID().toString().replaceAll("-", "").toUpperCase() + "\"," +
                    "    \"order_title\": \"向记账本里转入" + money + "\"," +
                    "    \"time_expire\": \"" + DateKit8.format2DateTime(DateKit8.addDays(new Date(), 1)) + "\"" +
                    "}");//设置业务参数
            //通过alipayClient调用API，获得对应的response类
            AlipayFundTransPagePayResponse response = alipayClient.pageExecute(request, "get");
            log.info("记账本id为：{}，调用支付宝生成向记账本里面转钱的链接：结果{}，入参{}",
                    accountBookId, response.getBody(), request.getBizContent());
            if (response.isSuccess()) {
                return response.getBody();
            } else {
                log.error("调用支付宝生成向记账本里面转钱的链接失败：支付宝返回结果{}", response.getBody());
                throw new ParamException(response.getSubMsg());
            }
        } catch (AlipayApiException e) {
            log.error("调用支付宝生成向记账本里面转钱的链接失败，e{}", e.getMessage());
            throw new ParamException("调用支付宝生成向记账本里面转钱的链接失败!" + e.getMessage());
        }
    }

    // 查询记账本
    public static AccountBookQueryVO selectAccountBook(CertAlipayRequest certAlipayRequest, String accountBookId, String agreementNo) {
        try {
            AlipayClient alipayClient = new DefaultAlipayClient(certAlipayRequest);
            AlipayFundAccountbookQueryRequest request = new AlipayFundAccountbookQueryRequest();
            request.setBizContent("{" +
                    "    \"scene_code\": \"SATF_FUND_BOOK\"," +
                    "    \"account_book_id\": \"" + accountBookId + "\"," +
                    "    \"merchant_user_type\": \"BUSINESS_ORGANIZATION\"," +
                    "    \"ext_info\": \"{\\\"agreement_no\\\":\\\"" + agreementNo + "\\\"}\"" +
                    "}");
            AlipayFundAccountbookQueryResponse response = alipayClient.certificateExecute(request);
            log.info("调用支付宝查询记账本：结果{}", response.getBody());
            String returnAccountBookId = response.getAccountBookId();
            String availableAmount = response.getAvailableAmount();
            if (StrKit.isEmpty(returnAccountBookId) || StrKit.isEmpty(availableAmount)) {
                throw new ParamException("调用支付宝查询记账本余额失败，支付宝返回结果：" + response.getBody());
            }
            AccountBookQueryVO accountBookQueryVO = new AccountBookQueryVO();
            accountBookQueryVO.setAccountBookId(accountBookId);
            accountBookQueryVO.setAvailableAmount(availableAmount);
            return accountBookQueryVO;
        } catch (AlipayApiException e) {
            log.error("调用支付宝查询记账本失败，e{}", e.getMessage());
            throw new ParamException("调用支付宝查询记账本失败!" + e.getMessage());
        }
    }

    // 单笔转账到户
    public static SafetyPayResultVO payOne(CertAlipayRequest certAlipayRequest, SafetyPayOneVO safetyPayOneVO) {
        try {
            // 设置固定值
            safetyPayOneVO.setProductCode("SINGLE_TRANSFER_NO_PWD");
            safetyPayOneVO.setBizScene("ENTRUST_TRANSFER");
            safetyPayOneVO.getPayerInfo().setIdentityType("ACCOUNT_BOOK_ID");
            safetyPayOneVO.getPayeeInfo().setIdentityType("ALIPAY_LOGON_ID");
            // 开始调用支付宝单笔转账到户
            DefaultAlipayClient alipayClient = new DefaultAlipayClient(certAlipayRequest);
            AlipayFundTransUniTransferRequest request = new AlipayFundTransUniTransferRequest();
            request.setBizContent(JSON.toJSONString(safetyPayOneVO));
            AlipayFundTransUniTransferResponse response = alipayClient.certificateExecute(request);
            log.info("调用单笔转账到户：支付宝返回结果：{}, 入参：{}", response.getBody(), JSON.toJSONString(safetyPayOneVO));
            SafetyPayResultVO safetyPayResultVO = new SafetyPayResultVO();
            safetyPayResultVO.setStatus(response.getStatus());
            if (response.isSuccess()) {
                safetyPayResultVO.setOutBizNo(response.getOutBizNo());
                safetyPayResultVO.setOrderId(response.getOrderId());
                safetyPayResultVO.setPayFundOrderId(response.getPayFundOrderId());
                safetyPayResultVO.setPayDate(response.getTransDate());
            } else {
                log.error("调用单笔转账到户失败：支付宝返回结果：{}", response.getBody());
                safetyPayResultVO.setSubMsg(response.getSubMsg());
                safetyPayResultVO.setSubCode(response.getSubCode());
            }
            return safetyPayResultVO;
        } catch (AlipayApiException e) {
            log.error("调用单笔转账到户失败，e{}", e.getMessage());
            throw new ParamException("调用单笔转账到户失败!" + e.getMessage());
        }
    }

    // 批量转账到户
    public static AlipayFundBatchUniTransferResponse payBatch(CertAlipayRequest certAlipayRequest) {
        try {
            AlipayClient alipayClient = new DefaultAlipayClient(certAlipayRequest);
            AlipayFundBatchUniTransferRequest request = new AlipayFundBatchUniTransferRequest();
            request.setBizContent("{" +
                    "    \"payer_info\": {" +
                    "        \"identity\": \"2088341129389431\"," +
                    "        \"identity_type\": \"ALIPAY_USER_ID\"," +
                    "        \"ext_info\": \"{\\\"agreement_no\\\":\\\"20215925784879369443\\\",\\\"account_book_id\\\":\\\"2088410300144849\\\",\\\"accountbook_scene_code\\\":\\\"SATF_FUND_BOOK\\\"}\"" +
                    "    }," +
                    "    \"trans_order_list\": [" +
                    "        {" +
                    "            \"payee_info\": {" +
                    "                \"identity\": \"15739966833\"," +
                    "                \"identity_type\": \"ALIPAY_LOGON_ID\"," +
                    "                \"name\": \"吴鸿\"" +
                    "            }," +
                    "            \"remark\": \"我是明细1的备注\"," +
                    "            \"trans_amount\": \"1\"," +
                    "            \"out_biz_no\": \"1\"" +
                    "        }," +
                    "        {" +
                    "            \"payee_info\": {" +
                    "                \"identity\": \"15739966899\"," +
                    "                \"identity_type\": \"ALIPAY_LOGON_ID\"," +
                    "                \"name\": \"吴鸿2\"" +
                    "            }," +
                    "            \"remark\": \"我是明细2的备注\"," +
                    "            \"trans_amount\": \"2\"," +
                    "            \"out_biz_no\": \"2\"" +
                    "        }" +
                    "    ]," +
                    "    \"remark\": \"我是批次备注\"," +
                    "    \"product_code\": \"BATCH_API_TO_ACC_NO_PWD\"," +
                    "    \"biz_scene\": \"MESSAGE_SATF_BATCH_PAY\"," +
                    "    \"total_count\": \"2\"," +
                    "    \"total_trans_amount\": \"3\"," +
                    "    \"out_batch_no\": \"202112170001whahy0004\"," +
                    "    \"order_title\": \"我是批次标题\"," +
                    "    \"business_params\": \"{\\\"agreement_no\\\":\\\"20215925784879369443\\\",\\\"fill_remark_of_staf_acct\\\":\\\"false\\\"}\"" +
                    "}");//设置业务参数
            System.out.println(request.getBizContent());
            AlipayFundBatchUniTransferResponse response = alipayClient.certificateExecute(request);
            log.info("调用支付宝批量无密代发：支付宝返回结果：{}, 入参：{}", response.getBody(), "JSON.toJSONString(safetyPayVO)");
            if (response.isSuccess()) {
                return response;
            } else {
                log.error("调用支付宝批量无密代发失败，支付宝返回结果：{}", response.getBody());
                throw new ParamException("调用支付宝批量无密代发失败! 支付宝错误信息：" + response.getSubMsg());
            }
        } catch (AlipayApiException e) {
            log.error("调用支付宝批量无密代发失败，e{}", e.getMessage());
            throw new ParamException("调用支付宝批量无密代发失败!" + e.getMessage());
        }
    }

    // 批量转账到户
    public static AlipayFundBatchUniTransferResponse payBatch(CertAlipayRequest certAlipayRequest, SafetyPayBatchVO safetyPayBatchVO) {
        try {
            // 设置固定值
            safetyPayBatchVO.getPayerInfo().setIdentityType("ALIPAY_USER_ID");
            safetyPayBatchVO.setProductCode("BATCH_API_TO_ACC_NO_PWD");
            safetyPayBatchVO.setBizScene("MESSAGE_SATF_BATCH_PAY");
            // 开始调用支付宝批量转账到户
            AlipayClient alipayClient = new DefaultAlipayClient(certAlipayRequest);
            AlipayFundBatchUniTransferRequest request = new AlipayFundBatchUniTransferRequest();
            //设置业务参数
            request.setBizContent(JSON.toJSONString(safetyPayBatchVO));
            AlipayFundBatchUniTransferResponse response = alipayClient.certificateExecute(request);
            log.info("调用支付宝批量无密代发：支付宝返回结果：{}, 入参：{}", response.getBody(), JSON.toJSONString(safetyPayBatchVO));
            if (response.isSuccess()) {
                return response;
            } else {
                log.error("调用支付宝批量无密代发失败，支付宝返回结果：{}", response.getBody());
                throw new ParamException("调用支付宝批量无密代发失败! 支付宝错误信息：" + response.getSubMsg());
            }
        } catch (AlipayApiException e) {
            log.error("调用支付宝批量无密代发失败，e{}", e.getMessage());
            throw new ParamException("调用支付宝批量无密代发失败!" + e.getMessage());
        }
    }

    // 根据outBizNo（自己设置的订单号）单笔转账查询
    public static BizContentSafety selectPayOne(CertAlipayRequest certAlipayRequest, String outBizNo) {
        try {
            AlipayClient alipayClient = new DefaultAlipayClient(certAlipayRequest);
            AlipayFundTransCommonQueryRequest request = new AlipayFundTransCommonQueryRequest();
            AlipayFundTransCommonQueryModel model = new AlipayFundTransCommonQueryModel();
            model.setOutBizNo(outBizNo);
            model.setBizScene("ENTRUST_TRANSFER");
            model.setProductCode("SINGLE_TRANSFER_NO_PWD");
            request.setBizModel(model);
            AlipayFundTransCommonQueryResponse response = alipayClient.certificateExecute(request);
            log.info("调用单笔转账查询：支付宝返回结果{}", response.getBody());
            if (response.isSuccess()) {
                BizContentSafety bizContentSafety = new BizContentSafety();
//                bizContentSafety.setOutBizNo(response.getOutBizNo());
//                bizContentSafety.setPayFundOrderId(response.getPayFundOrderId());
//                bizContentSafety.setOrderId(response.getOrderId());
//                bizContentSafety.setStatus(response.getStatus());
//                bizContentSafety.setTransAmount(response.getTransAmount());
//                bizContentSafety.setPayDate(response.getPayDate());
                return bizContentSafety;
            } else {
                log.error("调用单笔转账查询失败：支付宝返回结果{}", response.getBody());
                throw new ParamException("调用单笔转账查询失败：支付宝返回结果" + response.getSubMsg());
            }
        } catch (AlipayApiException e) {
            log.error("调用支付宝单笔转账查询失败，e{}", e.getMessage());
            throw new ParamException("调用支付宝单笔转账查询失败!" + e.getMessage());
        }
    }

    // 根据outBizNo（自己设置的订单号）批量转账查询
    public static AlipayFundBatchDetailQueryResponse selectPayBatch(CertAlipayRequest certAlipayRequest, String outBizNo, String agreementNo) {
        try {
            AlipayClient alipayClient = new DefaultAlipayClient(certAlipayRequest);
            AlipayFundBatchDetailQueryRequest request = new AlipayFundBatchDetailQueryRequest();
            request.setBizContent("{" +
                    "    \"product_code\": \"BATCH_API_TO_ACC_NO_PWD\"," +
                    "    \"biz_scene\": \"MESSAGE_SATF_BATCH_PAY\"," +
                    "    \"out_batch_no\": \"" + outBizNo + "\"," +
                    "    \"business_params\": {\"agreement_no\":\"" + agreementNo + "\"}" +
                    "}");
            AlipayFundBatchDetailQueryResponse response = alipayClient.certificateExecute(request);
            //根据response中的结果继续业务逻辑处理
            log.info("调用安全发批量转账查询：支付宝返回结果{}, 入参{}", response.getBody(), request.getBizContent());
            if (response.isSuccess()) {
                return response;
            } else {
                log.error("调用安全发批量转账查询失败：支付宝返回结果{}", response.getBody());
                throw new ParamException("调用安全发批量转账查询失败：支付宝返回结果:" + response.getSubMsg());
            }
        } catch (AlipayApiException e) {
            log.error("调用安全发批量转账查询失败，e{}", e.getMessage());
            throw new ParamException("调用安全发批量转账查询失败!" + e.getMessage());
        }
    }

    // 单笔转账到卡
    public static void payOneToBankCard(CertAlipayRequest certAlipayRequest, String agreementNo, String accountBookId) {
        try {
            DefaultAlipayClient alipayClient = new DefaultAlipayClient(certAlipayRequest);
            AlipayFundTransUniTransferRequest request = new AlipayFundTransUniTransferRequest();
            request.setBizContent("{" +
                    "\"out_biz_no\":\"20211222whahy0001\"," +
                    "\"trans_amount\":0.1," +
                    "\"product_code\":\"SINGLE_TRANSFER_NO_PWD\"," +
                    "\"biz_scene\":\"ENTRUST_TRANSFER\"," +
                    "\"order_title\":\"标题\"," +
                    "\"payee_info\":{" +
                    "\"identity\":\"6214835663660411\"," +
                    "\"identity_type\":\"BANKCARD_ACCOUNT\"," +
                    "\"name\":\"吴鸿\"," +
                    "\"bankcard_ext_info\":{\"account_type\": \"2\"} " +
                    "}," +
                    "\"remark\":\"备注\"," +
                    "\"payer_info\":{" +
                    "\"identity\":\"" + accountBookId + "\"," +
                    "\"identity_type\":\"ACCOUNT_BOOK_ID\"," +
                    " \"ext_info\": \"{\\\"agreement_no\\\":\\\"" + agreementNo + "\\\"}\"" +
                    " }" +
                    " }");
            AlipayFundTransUniTransferResponse response = alipayClient.certificateExecute(request);
            log.info("调用单笔转账到卡：支付宝返回结果：{}, 入参：{}", response.getBody(), "JSON.toJSONString(safetyPayOneVO)");
            if (response.isSuccess()) {
                System.out.println("调用成功");
            } else {
                System.out.println("调用失败");
            }
        } catch (AlipayApiException e) {
            log.error("调用单笔转账到卡失败，e{}", e.getMessage());
            throw new ParamException("调用单笔转账到卡失败!" + e.getMessage());
        }
    }

    // 单笔转账到卡
    public static AlipayFundTransUniTransferResponse payOneToBankCard(CertAlipayRequest certAlipayRequest, SafetyPayOneVO safetyPayOneVO) {
        try {
            DefaultAlipayClient alipayClient = new DefaultAlipayClient(certAlipayRequest);
            AlipayFundTransUniTransferRequest request = new AlipayFundTransUniTransferRequest();
            // 设置固定值
            safetyPayOneVO.setProductCode("SINGLE_TRANSFER_NO_PWD");
            safetyPayOneVO.setBizScene("ENTRUST_TRANSFER");
            safetyPayOneVO.getPayerInfo().setIdentityType("ACCOUNT_BOOK_ID");
            safetyPayOneVO.getPayeeInfo().setIdentityType("BANKCARD_ACCOUNT");
            BankCardExtInfoVO bankCardExtInfoVO = new BankCardExtInfoVO();
            bankCardExtInfoVO.setAccountType("2");
            safetyPayOneVO.getPayeeInfo().setBankcardExtInfo(bankCardExtInfoVO);
            request.setBizContent(JSON.toJSONString(safetyPayOneVO));
            AlipayFundTransUniTransferResponse response = alipayClient.certificateExecute(request);
            log.info("调用单笔转账到卡：支付宝返回结果：{}, 入参：{}", response.getBody(), JSON.toJSONString(safetyPayOneVO));
            if (response.isSuccess()) {
                return response;
            } else {
                log.error("调用单笔转账到卡失败, 失败信息:{}", response.getSubMsg());
                return response;
            }
        } catch (AlipayApiException e) {
            log.error("调用单笔转账到卡失败，e{}", e.getMessage());
            throw new ParamException("调用单笔转账到卡失败!" + e.getMessage());
        }
    }

}
